import { useEffect, useRef } from "react";
import * as echarts from "echarts";
import "echarts/lib/chart/heatmap";
import "echarts/lib/component/tooltip";
import "echarts/lib/component/visualMap";

const generateData = () => {
  const data = [];
  const year = new Date().getFullYear();
  for (let month = 0; month < 12; month++) {
    for (let day = 1; day <= 31; day++) {
      const date = new Date(year, month, day);
      if (date.getMonth() === month) {
        // 确保日期有效
        const value = Math.floor(Math.random() * 10); // 随机生成0-9之间的提交次数
        data.push([`${year}-${month + 1}-${day}`, value]);
      }
    }
  }
  return data;
};

const GithubHeatmap = () => {
  const chartRef = useRef(null);

  useEffect(() => {
    const chartInstance = echarts.init(chartRef.current);

    const data = generateData();

    const option = {
      tooltip: {
        position: "top",
        formatter: function (p: any) {
          const format: any = echarts.time.format;
          const value = p.data[1] || 0; // 如果没有提交，则显示0
          return `${format(
            p.data[0],
            "{yyyy}-{MM}-{dd}"
          )}<br/>Commits: ${value}`;
        },
      },
      visualMap: {
        min: 0,
        max: 10,
        calculable: true,
        orient: "horizontal",
        left: "center",
        bottom: "15%",
        inRange: {
          color: ["#ebedf0", "#c6e48b", "#7bc96f", "#239a3b", "#196127"],
        },
      },
      calendar: {
        top: "middle",
        left: "center",
        range: `${new Date().getFullYear()}`,
        cellSize: ["auto", 20],
        splitLine: {
          lineStyle: {
            color: "#ffffff",
            width: 2,
            type: "solid",
          },
        },
        itemStyle: {
          borderWidth: 1, // 设置边框宽度为1px
          borderColor: "#aaa5a5",
        },
        yearLabel: {
          show: false,
        },
        dayLabel: {
          firstDay: 1,
          nameMap: "en",
        },
        monthLabel: {
          nameMap: "en",
        },
      },
      series: [
        {
          type: "heatmap",
          coordinateSystem: "calendar",
          data: data,
        },
      ],
    };

    chartInstance.setOption(option);

    window.addEventListener("resize", () => {
      chartInstance.resize();
    });

    return () => {
      window.removeEventListener("resize", () => {
        chartInstance.resize();
      });
      chartInstance.dispose();
    };
  }, []);

  return (
    <div
      ref={chartRef}
      style={{
        width: "100%",
        height: "350px",
        // border: "1px solid #aaa5a5", // 添加边框包围图表
      }}
    />
  );
};

export default GithubHeatmap;
